// 存储键名常量
const STORAGE_KEYS = {
  DRINK_RECORDS: 'drink_records',
  DRINK_GOAL: 'drink_goal',
  TOILET_HISTORY: 'toilet_history',
  MOOD_HISTORY: 'mood_history',
  SLEEP_HISTORY: 'sleep_history',
  LAST_RESET_DATE: 'last_reset_date',
  USER_OPENID: 'user_openid',
  FORTUNE_DATA: 'fortune_data'
}

/**
 * 获取今日日期字符串 (YYYY-MM-DD)
 * @returns {String} 今日日期字符串
 */
export function getTodayString() {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

/**
 * 格式化日期为字符串 (YYYY-MM-DD)
 * @param {Date} date 日期对象
 * @returns {String} 格式化后的日期字符串
 */
export function formatDate(date) {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

/**
 * 检查并重置每日数据
 * 如果当前日期与上次重置日期不同，则重置相关数据
 */
export function resetDailyData() {
  const today = getTodayString()
  const lastResetDate = uni.getStorageSync(STORAGE_KEYS.LAST_RESET_DATE)
  
  // 如果今天已经重置过，则不再重置
  if (today === lastResetDate) {
    console.log('今日数据已重置，无需再次重置')
    return
  }
  
  console.log('重置每日数据...')
  
  // 记录重置日期
  uni.setStorageSync(STORAGE_KEYS.LAST_RESET_DATE, today)
  
  // 这里可以添加其他需要每日重置的数据
  // 例如：重置每日成就、每日任务等
}

/**
 * 获取今日情绪记录
 * @returns {Object|null} 今日情绪记录
 */
export function getTodayMoodRecord() {
  const today = getTodayString()
  const moodHistory = getMoodHistory()
  
  // 查找今日的情绪记录
  return moodHistory.find(item => item.date === today) || null
}

/**
 * 获取情绪历史记录
 * @returns {Array} 情绪历史记录数组
 */
export function getMoodHistory() {
  return uni.getStorageSync(STORAGE_KEYS.MOOD_HISTORY) || []
}

/**
 * 保存情绪记录
 * @param {Object} record 情绪记录对象
 */
export function saveMoodRecord(record) {
  const moodHistory = getMoodHistory()
  const today = getTodayString()
  
  // 检查是否已有今日记录
  const existingIndex = moodHistory.findIndex(item => item.date === today)
  
  if (existingIndex >= 0) {
    // 更新今日记录
    moodHistory[existingIndex] = record
  } else {
    // 添加新记录
    moodHistory.push(record)
  }
  
  // 保存到本地存储
  uni.setStorageSync(STORAGE_KEYS.MOOD_HISTORY, moodHistory)
}

/**
 * 获取今日睡眠记录
 * @returns {Object|null} 今日睡眠记录
 */
export function getTodaySleepRecord() {
  const today = getTodayString()
  const sleepHistory = getSleepHistory()
  
  // 查找今日的睡眠记录
  return sleepHistory.find(item => item.date === today) || null
}

/**
 * 获取睡眠历史记录
 * @returns {Array} 睡眠历史记录数组
 */
export function getSleepHistory() {
  return uni.getStorageSync(STORAGE_KEYS.SLEEP_HISTORY) || []
}

/**
 * 保存睡眠记录
 * @param {Object} record 睡眠记录对象
 */
export function saveSleepRecord(record) {
  const sleepHistory = getSleepHistory()
  const today = getTodayString()
  
  // 检查是否已有今日记录
  const existingIndex = sleepHistory.findIndex(item => item.date === today)
  
  if (existingIndex >= 0) {
    // 更新今日记录
    sleepHistory[existingIndex] = record
  } else {
    // 添加新记录
    sleepHistory.push(record)
  }
  
  // 保存到本地存储
  uni.setStorageSync(STORAGE_KEYS.SLEEP_HISTORY, sleepHistory)
}

/**
 * 获取今日如厕记录
 * @returns {Array} 今日如厕记录数组
 */
export function getTodayToiletRecords() {
  const today = getTodayString()
  return getToiletHistory().filter(item => item.date === today)
}

/**
 * 获取如厕历史记录
 * @returns {Array} 如厕历史记录数组
 */
export function getToiletHistory() {
  return uni.getStorageSync(STORAGE_KEYS.TOILET_HISTORY) || []
}

/**
 * 保存如厕记录
 * @param {Object} record 如厕记录对象
 */
export function saveToiletRecord(record) {
  const toiletHistory = getToiletHistory()
  
  // 添加新记录
  toiletHistory.push(record)
  
  // 保存到本地存储
  uni.setStorageSync(STORAGE_KEYS.TOILET_HISTORY, toiletHistory)
}

/**
 * 获取今日如厕次数
 * @returns {Number} 今日如厕次数
 */
export function getTodayToiletCount() {
  return getTodayToiletRecords().length
}

/**
 * 获取饮水记录
 * @returns {Array} 饮水记录数组
 */
export function getDrinkRecords() {
  return uni.getStorageSync(STORAGE_KEYS.DRINK_RECORDS) || []
}

/**
 * 保存饮水记录
 * @param {Object} record 饮水记录对象
 */
export function saveDrinkRecord(record) {
  const records = getDrinkRecords()
  records.push(record)
  uni.setStorageSync(STORAGE_KEYS.DRINK_RECORDS, records)
}

/**
 * 获取今日饮水量
 * @returns {Number} 今日饮水量(ml)
 */
export function getTodayDrinkAmount() {
  const today = getTodayString()
  const records = getDrinkRecords()
  
  // 过滤出今日记录并计算总量
  return records
    .filter(record => record.date === today)
    .reduce((total, record) => total + record.amount, 0)
}

/**
 * 获取昨日饮水量
 * @returns {Number} 昨日饮水量(ml)
 */
export function getYesterdayDrinkAmount() {
  const yesterday = new Date()
  yesterday.setDate(yesterday.getDate() - 1)
  const yesterdayStr = formatDate(yesterday)
  
  const records = getDrinkRecords()
  
  // 过滤出昨日记录并计算总量
  return records
    .filter(record => record.date === yesterdayStr)
    .reduce((total, record) => total + record.amount, 0)
}

/**
 * 获取饮水目标
 * @returns {Number} 饮水目标(ml)
 */
export function getDrinkGoal() {
  return uni.getStorageSync(STORAGE_KEYS.DRINK_GOAL) || 2000
}

/**
 * 设置饮水目标
 * @param {Number} goal 饮水目标(ml)
 */
export function setDrinkGoal(goal) {
  uni.setStorageSync(STORAGE_KEYS.DRINK_GOAL, goal)
}

/**
 * 获取用户openid
 * @returns {String} 用户openid
 */
export function getLocalOpenid() {
  return uni.getStorageSync(STORAGE_KEYS.USER_OPENID) || ''
}

/**
 * 保存用户openid
 * @param {String} openid 用户openid
 */
export function saveLocalOpenid(openid) {
  uni.setStorageSync(STORAGE_KEYS.USER_OPENID, openid)
}

/**
 * 获取今日情绪
 * @returns {Object|null} 今日情绪记录
 */
export function getTodayMood() {
  return getTodayMoodRecord()
}

/**
 * 获取今日睡眠
 * @returns {Object|null} 今日睡眠记录
 */
export function getTodaySleep() {
  return getTodaySleepRecord()
}

/**
 * 计算健康指数
 * 根据饮水量、情绪记录、睡眠记录和如厕次数计算健康指数
 * @returns {Object} 健康指数对象，包含总分和各项分数
 */
export function getHealthIndex() {
  // 获取各项数据
  const waterAmount = getTodayDrinkAmount()
  const waterGoal = getDrinkGoal()
  const moodRecord = getTodayMood()
  const sleepRecord = getTodaySleep()
  const toiletCount = getTodayToiletCount()
  
  // 计算饮水指数 (0-100)
  const waterIndex = Math.min(100, Math.round((waterAmount / waterGoal) * 100))
  
  // 计算情绪指数 (0-100)
  const moodIndex = moodRecord ? 100 : 0
  
  // 计算睡眠指数 (0-100)
  const sleepIndex = sleepRecord ? 100 : 0
  
  // 计算如厕指数 (0-100)，假设正常如厕次数为3-5次
  let toiletIndex = 0
  if (toiletCount >= 3 && toiletCount <= 5) {
    toiletIndex = 100
  } else if (toiletCount > 0) {
    toiletIndex = 70
  }
  
  // 计算总健康指数 (各项指数的平均值)
  const totalIndex = Math.round((waterIndex + moodIndex + sleepIndex + toiletIndex) / 4)
  
  return {
    total: totalIndex,
    water: {
      amount: waterAmount,
      goal: waterGoal,
      percentage: waterIndex
    },
    mood: {
      hasRecord: !!moodRecord,
      type: moodRecord ? moodRecord.type : '',
      score: moodIndex
    },
    sleep: {
      hasRecord: !!sleepRecord,
      quality: sleepRecord ? sleepRecord.quality : '',
      score: sleepIndex
    },
    toilet: {
      count: toiletCount,
      index: toiletIndex
    }
  }
}

/**
 * 获取今日运势
 * @returns {String} 今日运势文本
 */
export function getTodayFortune() {
  const today = getTodayString()
  const fortuneData = uni.getStorageSync(STORAGE_KEYS.FORTUNE_DATA) || {}
  
  // 如果今日已有运势，则返回
  if (fortuneData[today]) {
    return fortuneData[today]
  }
  
  // 默认运势
  const defaultFortune = '今天是美好的一天，记得多喝水，保持健康的生活习惯...'
  
  // 保存默认运势
  fortuneData[today] = defaultFortune
  uni.setStorageSync(STORAGE_KEYS.FORTUNE_DATA, fortuneData)
  
  return defaultFortune
}

/**
 * 记录每日打卡
 * 用于记录用户每日首次打开应用
 */
export function recordDailyCheckin() {
  const today = getTodayString()
  const checkinHistory = uni.getStorageSync('daily_checkin_history') || {}
  
  // 如果今天已经打卡过，则不再记录
  if (checkinHistory[today]) {
    return
  }
  
  // 记录今日打卡
  checkinHistory[today] = {
    date: today,
    timestamp: Date.now()
  }
  
  uni.setStorageSync('daily_checkin_history', checkinHistory)
  
  // 重置每日数据
  resetDailyData()
}

// 导出 STORAGE_KEYS 常量
export { STORAGE_KEYS }